const vscode = require("vscode");
const { colors } = require("../webview/colors/colors");
const { validatorColorDocument } = require("./Validator");

function registerColorCompletionItemProvider(context) {
  const colorsProvider = vscode.languages.registerCompletionItemProvider(
    "mirtxt",
    ColorCompletionItemProvider,
    "="
  );
  context.subscriptions.push(colorsProvider);

  // 注册触发命令
  const triggerCommand = vscode.commands.registerCommand(
    "extension-mir-script.showColorPicker",
    () => {
      global.isCommandTriggered = true;
      // 执行两步操作：
      vscode.commands
        .executeCommand("editor.action.triggerSuggest")
        .then(() => {
          // 重置状态（延迟确保补全列表弹出）
          setTimeout(() => (global.isCommandTriggered = false), 500);
        });
    }
  );
  context.subscriptions.push(colorsProvider, triggerCommand);
}

const ColorCompletionItemProvider = {
  provideCompletionItems(document, position) {
    const linePrefix = document
      .lineAt(position)
      .text.slice(0, position.character);

    if (!validatorColorDocument(linePrefix) && !global.isCommandTriggered) {
      return undefined;
    }

    const list = [];
    colors.forEach((color) => {
      list.push({
        detail: `${color.hex}`,
        documentation: color.number,
        kind: vscode.CompletionItemKind.Color,
        filterText: color.number,
        label: `${color.number}`,
        insertText: color.number,
      });
    });
    return list;
  },
};

module.exports = { registerColorCompletionItemProvider };
